from concurrent import futures
import logging
import time
import grpc
import test_pb2
import test_pb2_grpc

global server

class StreamTest(test_pb2_grpc.StreamTestServicer):
    def BothStream(self, request_iterator, context):
        for i in request_iterator:
            print("客户端发送：", i.message)

        for i in ['a', 'b', 'c', 'd', 'e', 'f', 'g']:
            time.sleep(1)
            yield test_pb2.response(message=i)


def serve():
    global server
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    test_pb2_grpc.add_StreamTestServicer_to_server(StreamTest(), server)
    server.add_insecure_port("0.0.0.0:10086")
    server.start()
    # server.wait_for_termination()  # 要关闭grpc server必须注释该行代码，然后等待固定时间关闭服务器


def close_grpc():
    global server
    server.stop(0)
    print("close grpc server")


if __name__ == "__main__":
    logging.basicConfig()
    serve()
    time.sleep(20)
    close_grpc()


